﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Bright.Common;
using Mono.CSharp;
using Enum = System.Enum;

namespace Gp.Scripts.Core
{
    public partial class UnitStat
    {
        private Dictionary<int, FieldInfo> _mapDic;
        
        public int this[int statId] => (int) GetFieldInfo(statId).GetValue(this);

        private FieldInfo GetFieldInfo(int statId)
        {
            _mapDic ??= new Dictionary<int, FieldInfo>();
            if (_mapDic.TryGetValue(statId, out var ret)) return ret;
            
            var statTable = Global.GetConfig<Unit.TableStatField>();
            var conf      = statTable.Get(statId);
            if (conf == null) throw new ArgumentException($"key 不存在 {statId}");
            var keyName   = conf.KeyName;
            var fieldInfo = GetType().GetField(keyName.ToPascal(), BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
            if (fieldInfo == null) throw new Exception($"StatField 数值表格配置错误: keyName：[{conf.KeyName}] not match, {conf}");
            _mapDic[statId] = fieldInfo;

            return _mapDic[statId];
        }

        public static IEnumerable<Unit.ConfigStatField> AllFieldConfigs()
        {
            return Global.GetConfig<Unit.TableStatField>().DataList;
        }
    }
}